<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>图片搜索App</title>
  <link rel="stylesheet" href="style.css" />
  <script src="./axios.js"></script>
</head>

<body>
  <h1>图片搜索</h1>
  <form>
    <input type="text" id="search-input" placeholder="搜索图片" />
    <button id="search-button">搜索</button>
  </form>
  <div class="search-results">
  </div>
  <button id="show-more-button">显示更多</button>
  <script>
    //点击搜索按钮，如果输入内容为空，弹出提示
    //如果有数据，渲染数据，如果没有数据，展示提示
    let page = 1
    // let imgstr = ''
    const searchInput = document.querySelector('#search-input')
    const searchButton = document.querySelector('#search-button')
    searchButton.addEventListener('click', function (e) {
      // 阻止默认行为
      e.preventDefault()
      const value = searchInput.value.trim()
      if (value === '') {
        alert('请输入搜索内容')
        return
      }
      console.log(value)
      render(value, page)
    })

    //数据渲染
    async function render(title, page) {
      let data = {
        _page: page,
        _limit: 6,
        title_like: title
      }
      let res = await axios.get('https://jsonplaceholder.typicode.com/photos', { params: data })
      let imgData = res.data
      renderImg(imgData)
      //渲染“显示更多”按钮
      let moreNode = await document.querySelector('#show-more-button')
      if (imgData.length === 0) {
        moreNode.style.display = 'none'
        return
      }
      moreNode.style.display = 'block'
      moreNode.onclick = function () {
        page++
        render(title, page)
      }
    }

    //渲染图片
    function renderImg(data) {
      let imgstr = data.map(item => `<div class="search-result">
      <img
        src="${item.url}"
        alt="image" />
      <a href="${item.thumbnailUrl}" target="_blank" rel="noopener noreferrer">an image of a
        beach</a>
    </div>`
      ).join('')
      document.querySelector('.search-results').innerHTML += imgstr
    }

    //点击更多按钮，加载下一页数据

  </script>

</body>

</html>